package mdm.led.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mdm.led.common.AjaxResponse;
import mdm.led.common.BaseController;
import mdm.led.common.Constant;
import mdm.led.entity.SysBackup;
import mdm.led.entity.three.ThreeTaskSelf;
import mdm.led.log.OperationLog;
import mdm.led.service.ISystemService;
import mdm.led.util.MySqlDBUtil;
import mdm.led.util.session.TokenUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "system")
@Api(description = Constant.MODULE_SYSTEM)
public class SystemController extends BaseController {
	private static final Logger LOGGER = LoggerFactory.getLogger(SystemController.class);

	private final ISystemService iSystemService;

	@Autowired
	public SystemController(ISystemService iSystemService) {
		this.iSystemService = iSystemService;
	}

	@ApiOperation(value = "数据库备份")
	@OperationLog(operationModule = Constant.MODULE_SYSTEM, operationFunction = "数据库备份")
	@ResponseBody
	@RequestMapping(value = "/backup", method = RequestMethod.POST)
	public AjaxResponse backup(HttpServletRequest request) {
		try {
			SysBackup sysBackup = iSystemService.selectByBackupTime(new Date());
			if (sysBackup != null) {
				return AjaxResponse.reponseBody(Constant.CHECK_CODE, super.getMessage("backup_too_frequently"), null);
			}

			Integer userId = TokenUtil.getUserId(TokenUtil.getToken(request));
			if (userId > 0) {
				iSystemService.backup(userId);
				return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, "备份成功");
			} else {
				return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, "登录失效");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "出现异常");
		}
	}

	@ApiOperation(value = "数据库还原", notes = "请求参数<br>" + "cBackupId 备份点id")
	@OperationLog(operationModule = Constant.MODULE_SYSTEM, operationFunction = "数据库还原")
	@ResponseBody
	@RequestMapping(value = "/restore", method = RequestMethod.GET)
	public AjaxResponse restore(@RequestParam("cBackupId") Integer cBackupId) {
		try {
			LOGGER.info("--------------restore id: {}", cBackupId);
			if (cBackupId == null) {
				return AjaxResponse.reponseBody(Constant.CHECK_CODE, super.getMessage("backup_check_restore_id"), null);
			}

			String username = super.localConfig.getUsername();
			String password = super.localConfig.getPassword();
			String database = super.localConfig.getDatabase();
			String mysqlPath = super.localConfig.getMysql_path();
			SysBackup sysBackup = iSystemService.selectByPrimaryKey(cBackupId);
			String filePath = super.localConfig.getSystem_backup() + sysBackup.getcBackupFile();

			MySqlDBUtil.restoreDB(username, password, database, filePath);

			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
		} catch (Exception e) {
			LOGGER.error("", e);
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}

	@ApiOperation(value = "删除备份", notes = "请求参数<br>" + "cBackupId 备份点id")
	@OperationLog(operationModule = Constant.MODULE_SYSTEM, operationFunction = "备份删除")
	@ResponseBody
	@RequestMapping(value = "/remove/{cBackupId}", method = RequestMethod.DELETE)
	public AjaxResponse delete(@PathVariable Integer cBackupId) {
		try {
			LOGGER.info("--------------restore id: {}", cBackupId);
			if (cBackupId == null) {
				return AjaxResponse.reponseBody(Constant.CHECK_CODE, super.getMessage("backup_check_delete_id"), null);
			}
			iSystemService.removeById(cBackupId);
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
		} catch (Exception e) {
			LOGGER.error("", e);
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}

	@ApiOperation(value = "查询备份", notes = "请求参数:<br>" + "pageIndex 页码<br>" + "limit 每页显示条数<br>" + "可选查询条件:<br>"
			+ "startDate 开始时间<br>" + "endDate 结束时间")
	@OperationLog(operationModule = Constant.MODULE_SYSTEM, operationFunction = "查询备份")
	@ResponseBody
	@RequestMapping(value = "/page", method = RequestMethod.POST)
	public AjaxResponse page(@RequestBody SysBackup sysBackup, @RequestParam Integer currPage,
			@RequestParam Integer pageSize) {

		LOGGER.info("-----查询备份-------param:{}---{}---{}", sysBackup, currPage, pageSize);
		boolean flag = false;
		// 需要返回的 map 数据集合
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			// 开启分页
			Page<SysBackup> page = PageHelper.startPage(currPage, pageSize);
			List<SysBackup> list = iSystemService.selectByCondition(sysBackup);
			// 数据
			data.put("list", list);
			// 当前页
			data.put("currPage", page.getPageNum());
			// 页总数
			data.put("pageCount", page.getPages());
			// 页大小
			data.put("pageSize", page.getPageSize());
			// 总条数
			data.put("totalCount", page.getTotal());
			flag = true;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		LOGGER.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		LOGGER.info("\n======== 结果值 : \n" + JSON.toJSONString(data) + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, data);
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "异常");
		}

	}
}